<script setup lang="ts">
import type { FormRules } from "element-plus"
import type { LoginRequestData } from "./apis/type"
// import { Key, Loading, Lock, Picture, User } from "@element-plus/icons-vue"
import { useSettingsStore } from "@/pinia/stores/settings"
import { useUserStore } from "@/pinia/stores/user"
import { loginApi } from "./apis"
import { useFocus } from "./composables/useFocus"
import { getWechatLoginUrl  } from "@/api"
const router = useRouter()
const iframeUrl = ref("https://www.sacasaca.com/wechatloginqrocde.html")
const userStore = useUserStore()

const settingsStore = useSettingsStore()
const dialogVisible = ref(false)
const { isFocus, handleBlur, handleFocus } = useFocus()
const timer = null;
const checked = ref(true)
/** 登录表单元素的引用 */
const loginFormRef = useTemplateRef("loginFormRef")

/** 登录按钮 Loading */
const loading = ref(false)

// 处理微信登录回调
// 微信扫码成功后，会跳转到你在后端配置的 redirect_uri，
// 页面 URL 会变成这样：http://yourdomain.com/login-callback?code=xxx&state=yyy
// 你需要一个专门的页面或在当前页面处理这个回调
onMounted(() => {
  // initWechatLogin();
  let codeString = ''
  let codeString2 = ''
  let step = 1
  const href = window.location.href;
  if ( href.indexOf('?') > -1) {
    const params = href.split('?')
    console.log(params);
    if (params[1]) {
      const bbb = params[1]
      const paramsArray2 = bbb.split('&')
      console.log(paramsArray2);
      if (paramsArray2[0].indexOf('id=')> -1 && paramsArray2[1].indexOf('token=')> -1 && paramsArray2[2].indexOf('username=')> -1 ) {
        const id = paramsArray2[0].split('=')[1]
        const token = paramsArray2[1].split('=')[1]
        const username = decodeURI(paramsArray2[2].split('=')[1])
        iframeUrl .value= ''
        dialogVisible.value = false
        console.log( "token:" + token)
        userStore.setUsername(username) // token-admin
        userStore.setToken(token) // token-admin
        userStore.setUserId( parseInt(id)) // token-admin
        window.top.location.href = "/"
        // document.getElementById("homeLink").click();
        // 保存到cookie中
      }
    }
  } else {
    // dialogVisible.value = true
    console.log("初次访问");
    let currentDomain = window.location.hostname;
    if (currentDomain === 'sacasaca.com') {
      location.href='https://www.sacasaca.com';
    }
  }
})
/** 登录表单数据 */
const loginFormData: LoginRequestData = reactive({
  username: "",
  account: "",
  password: "",
  mobile: "",
  code: ""
})

/** 登录表单校验规则 */
const loginFormRules: FormRules = {
  account: [
    { required: true, message: "请输入用户名/账号", trigger: "blur" },
    // 判断手机号码格式
     {
       validator: (rule, value, callback) => {
         if (!value) {
           callback(new Error("请输入手机号码"))
         } else if (!/^1[3456789]\d{9}$/.test(value)) {
           callback(new Error("请输入正确的手机号码"))
         } else {
           callback()
         }
       }
     }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" }
  ],
  code: [
  ]
}
/** 登录 */
function handleLogin() {
  if (!checked.value) {
    ElMessage.error({
      message: "登录前，请先同意服务条款和隐私条款！",
      type: "warning",
      duration: 1000
    })
    return false
  }
  loginFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    loginFormData.username = loginFormData.account
    loginFormData.mobile = loginFormData.account
    loading.value = true
    loginApi(loginFormData).then(({ data }) => {
      userStore.setUsername(data.mobile) // token-admin
      userStore.setToken(data.token) // token-admin
      userStore.setUserId(data.id) // token-admin
      router.push("/")
    }).catch(() => {
      ElMessage.error({
        message: "验证失败，消息将在 2 秒后关闭",
        type: "warning",
        duration: 2000
      })
      // loginFormData.password = ""
    }).finally(() => {
      loading.value = false
    })
  })
}


function onIframeLoad() {
  // iframe加载完成后的处理
  const iframe = document.getElementById('searchshow');
  if (!iframe) return;

  // 设置默认高度，根据用户偏好使用100vh而不是固定像素值
  // iframe.style.height = '100vh';

  // 设置消息监听器
  setupMessageListener();
}
function handleIframeMessage(event) {
  if (event.data && typeof event.data === 'object' && event.data.type === 'resize') {
    const iframe = document.getElementById('searchshow');
    if (iframe && event.data.height) {
      iframe.style.height = `${event.data.height}px`;
      console.log(`收到高度更新: ${event.data.height}px, 视图模式: ${event.data.viewMode || '未指定'}`);
    }
  }
}
function handleClose(done) {
  // 在关闭前移除消息监听器
  removeMessageListener();
  done();
}
function onDialogClosed() {
  console.log('对话框已完全关闭');
  // 确保消息监听器被移除
  removeMessageListener();
}
// 由于跨域限制，我们不能直接访问iframe内容
// 使用消息机制来处理iframe高度
function setupMessageListener()
{
  // 先移除可能存在的旧监听器，避免重复添加
  removeMessageListener();
  // 添加消息事件监听器
  window.addEventListener('message', handleIframeMessage);
  console.log('已设置消息监听器');
}
function removeMessageListener() {
  // 移除消息事件监听器
  window.removeEventListener('message', handleIframeMessage);
  console.log('已移除消息监听器');
}
function showQRCode() {
  dialogVisible.value = false
}
</script>

<template>
  <div class="container child-view" style="max-width: 2536px;">
    <!--<el-dialog
      v-model="dialogVisible"
      style="width: 350px;height:490px; overflow: hidden;"
      :before-close="handleClose"
      destroy-on-close
      @closed="onDialogClosed"
    >
      <iframe :src="iframeUrl" id="searchshow" frameborder="0" style="width: 350px; height: 450px;overflow: hidden; " scroll="no" ref="iframeRef" @load="onIframeLoad">
        <div id="wechat-login-container" style="height: 350px;margin-top: 50px;overflow-y: hidden"></div>
      </iframe>

    </el-dialog>-->
    <div class="content">
      <div class="tab-nav">
        <div class="tab-item current" @click="showQRCode">
          微信登录
        </div>
        <a href="/#/login" class="">
          <div class="tab-item">
            密码登录
          </div></a>
      </div>
      <div class="form-content">
        <div style="width: 500px;height: 420px;text-align: center;overflow: hidden;">

          <iframe :src="iframeUrl" id="searchshow" frameborder="0" style="width: 350px; height: 550px;overflow: hidden; " scroll="no" ref="iframeRef" @load="onIframeLoad"></iframe>
        </div>
        <div class="tip">
          <div class="hasAccout">
            <span>还没有账号？</span>
            <a href="/#/register" class=""><span class="goLogin">立即注册</span></a>
          </div>
          <div class="forget">
            <a href="/#/" class="" id="homeLink" ><span class="forget-text">返回首页</span></a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<style src="@/pages/login/style/wechatlogin.css"  scoped></style>
<style>
</style>
